import { prisma } from '../db/prisma';
import { createSuccessResponse, createErrorResponse } from '../utils/response';
import bcrypt from 'bcrypt';
import { z } from 'zod';
import { TimerService } from './timerService';

// 输入验证 schema
const createManagerSchema = z.object({
  username: z.string().min(3).max(50),
  password: z.string().min(6).max(100),
  fullName: z.string().min(1).max(50),
});

const updateManagerSchema = z.object({
  id: z.number().int().positive(),
  username: z.string().min(3).max(50).optional(),
  password: z.string().min(6).max(100).optional(),
  fullName: z.string().min(1).max(50).optional(),
});

const deleteManagerSchema = z.object({
  id: z.number().int().positive(),
});

const getManagerSchema = z.object({
  id: z.number().int().positive(),
});

const listManagersSchema = z.object({
  page: z.number().int().positive().default(1),
  pageSize: z.number().int().positive().max(100).default(10),
  search: z.string().optional(),
});

const getManagerClientsSchema = z.object({
  managerId: z.number().int().positive(),
  page: z.number().int().positive().default(1),
  pageSize: z.number().int().positive().max(100).default(10),
  search: z.string().optional(),
});

export class ManagerService {
  // 创建客户经理
  static async createManager(input: z.infer<typeof createManagerSchema>) {
    try {
      const validatedInput = createManagerSchema.parse(input);
      
      // 检查用户名是否已存在（包括已删除的）
      const existingManager = await prisma.manager.findUnique({
        where: { username: validatedInput.username }
      });
      
      if (existingManager) {
        return createErrorResponse('用户名已存在', 'USERNAME_EXISTS');
      }
      
      // 加密密码
      const saltRounds = 10;
      const passwordHash = await bcrypt.hash(validatedInput.password, saltRounds);
      
      // 创建客户经理
      const manager = await prisma.manager.create({
        data: {
          username: validatedInput.username,
          passwordHash,
          fullName: validatedInput.fullName,
        },
        select: {
          id: true,
          username: true,
          fullName: true,
          createdAt: true,
          updatedAt: true,
        }
      });
      
      return createSuccessResponse(manager, '客户经理创建成功');
    } catch (error) {
      console.error('创建客户经理失败:', error);
      if (error instanceof z.ZodError) {
        return createErrorResponse('输入数据验证失败', 'VALIDATION_ERROR', error.errors);
      }
      return createErrorResponse('创建客户经理失败', 'CREATE_MANAGER_ERROR');
    }
  }
  
  // 更新客户经理
  static async updateManager(input: z.infer<typeof updateManagerSchema>) {
    try {
      const validatedInput = updateManagerSchema.parse(input);
      
      // 检查客户经理是否存在
      const existingManager = await prisma.manager.findUnique({
        where: { 
          id: validatedInput.id
        }
      });
      
      if (!existingManager) {
        return createErrorResponse('客户经理不存在', 'MANAGER_NOT_FOUND');
      }
      
      // 如果要更新用户名，检查是否与其他用户冲突（包括已删除的）
      if (validatedInput.username && validatedInput.username !== existingManager.username) {
        const usernameExists = await prisma.manager.findUnique({
          where: { username: validatedInput.username }
        });
        
        if (usernameExists) {
          return createErrorResponse('用户名已存在', 'USERNAME_EXISTS');
        }
      }
      
      // 准备更新数据
      const updateData: any = {};
      if (validatedInput.username) updateData.username = validatedInput.username;
      if (validatedInput.fullName) updateData.fullName = validatedInput.fullName;
      if (validatedInput.password) {
        const saltRounds = 10;
        updateData.passwordHash = await bcrypt.hash(validatedInput.password, saltRounds);
      }
      
      // 更新客户经理
      const manager = await prisma.manager.update({
        where: { id: validatedInput.id },
        data: updateData,
        select: {
          id: true,
          username: true,
          fullName: true,
          createdAt: true,
          updatedAt: true,
        }
      });
      
      return createSuccessResponse(manager, '客户经理更新成功');
    } catch (error) {
      console.error('更新客户经理失败:', error);
      if (error instanceof z.ZodError) {
        return createErrorResponse('输入数据验证失败', 'VALIDATION_ERROR', error.errors);
      }
      return createErrorResponse('更新客户经理失败', 'UPDATE_MANAGER_ERROR');
    }
  }
  
  // 硬删除客户经理
  static async deleteManager(input: z.infer<typeof deleteManagerSchema>) {
    try {
      const validatedInput = deleteManagerSchema.parse(input);
      
      // 检查客户经理是否存在
      const existingManager = await prisma.manager.findUnique({
        where: { 
          id: validatedInput.id
        }
      });
      
      if (!existingManager) {
        return createErrorResponse('客户经理不存在', 'MANAGER_NOT_FOUND');
      }
      
      // 硬删除客户经理（级联删除相关数据）
      await prisma.manager.delete({
        where: { id: validatedInput.id }
      });
      
      // 删除成功后，立即触发客户清理检查
      TimerService.triggerImmediateCleanup().catch(error => {
        console.error('删除客户经理后触发的客户清理失败:', error);
      });
      
      return createSuccessResponse(null, '客户经理删除成功');
    } catch (error) {
      console.error('删除客户经理失败:', error);
      if (error instanceof z.ZodError) {
        return createErrorResponse('输入数据验证失败', 'VALIDATION_ERROR', error.errors);
      }
      return createErrorResponse('删除客户经理失败', 'DELETE_MANAGER_ERROR');
    }
  }
  
  // 获取单个客户经理
  static async getManager(input: z.infer<typeof getManagerSchema>) {
    try {
      const validatedInput = getManagerSchema.parse(input);
      
      const manager = await prisma.manager.findUnique({
        where: { 
          id: validatedInput.id
        },
        select: {
          id: true,
          username: true,
          fullName: true,
          createdAt: true,
          updatedAt: true,
          _count: {
            select: {
              clientAssignments: true,
              workLogs: true,
            }
          }
        }
      });
      
      if (!manager) {
        return createErrorResponse('客户经理不存在', 'MANAGER_NOT_FOUND');
      }
      
      return createSuccessResponse(manager, '获取客户经理成功');
    } catch (error) {
      console.error('获取客户经理失败:', error);
      if (error instanceof z.ZodError) {
        return createErrorResponse('输入数据验证失败', 'VALIDATION_ERROR', error.errors);
      }
      return createErrorResponse('获取客户经理失败', 'GET_MANAGER_ERROR');
    }
  }
  
  // 获取客户经理列表
  static async listManagers(input: z.infer<typeof listManagersSchema>) {
    try {
      const validatedInput = listManagersSchema.parse(input);
      const { page, pageSize, search } = validatedInput;
      
      // 构建查询条件
      const where: any = {};
      
      if (search) {
        where.OR = [
          { username: { contains: search } },
          { fullName: { contains: search } },
        ];
      }
      
      // 获取总数
      const total = await prisma.manager.count({ where });
      
      // 获取分页数据
      const managers = await prisma.manager.findMany({
        where,
        select: {
          id: true,
          username: true,
          fullName: true,
          createdAt: true,
          updatedAt: true,
          _count: {
            select: {
              clientAssignments: true,
              workLogs: true,
            }
          }
        },
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * pageSize,
        take: pageSize,
      });
      
      const result = {
        data: managers,
        pagination: {
          page,
          pageSize,
          total,
          totalPages: Math.ceil(total / pageSize),
        }
      };
      
      return createSuccessResponse(result, '获取客户经理列表成功');
    } catch (error) {
      console.error('获取客户经理列表失败:', error);
      if (error instanceof z.ZodError) {
        return createErrorResponse('输入数据验证失败', 'VALIDATION_ERROR', error.errors);
      }
      return createErrorResponse('获取客户经理列表失败', 'LIST_MANAGERS_ERROR');
    }
  }

  // 获取客户经理的客户列表
  static async getManagerClients(input: z.infer<typeof getManagerClientsSchema>) {
    try {
      const validatedInput = getManagerClientsSchema.parse(input);
      const { managerId, page, pageSize, search } = validatedInput;

      // 检查客户经理是否存在
      const manager = await prisma.manager.findUnique({
        where: { 
          id: managerId
        },
        select: { id: true, fullName: true }
      });

      if (!manager) {
        return createErrorResponse('客户经理不存在', 'MANAGER_NOT_FOUND');
      }

      // 构建查询条件
      const where: any = {
        managerAssignments: {
          some: {
            managerId: managerId
          }
        }
      };

      if (search) {
        where.OR = [
          { clientCode: { contains: search } },
          { clientName: { contains: search } },
        ];
      }

      // 获取总数
      const total = await prisma.client.count({ where });

      // 获取分页数据
      const clients = await prisma.client.findMany({
        where,
        select: {
          id: true,
          clientCode: true,
          clientName: true,
          marketType: true,
          terminalType: true,
          createdAt: true,
          serviceAssignments: {
            select: {
              service: {
                select: {
                  id: true,
                  serviceName: true,
                }
              }
            }
          },
          _count: {
            select: {
              workLogs: true,
            }
          }
        },
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * pageSize,
        take: pageSize,
      });

      const result = {
        manager: manager,
        data: clients,
        pagination: {
          page,
          pageSize,
          total,
          totalPages: Math.ceil(total / pageSize),
        }
      };

      return createSuccessResponse(result, '获取客户经理客户列表成功');
    } catch (error) {
      console.error('获取客户经理客户列表失败:', error);
      if (error instanceof z.ZodError) {
        return createErrorResponse('输入数据验证失败', 'VALIDATION_ERROR', error.errors);
      }
      return createErrorResponse('获取客户经理客户列表失败', 'GET_MANAGER_CLIENTS_ERROR');
    }
  }
}
